from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from linear_regression.MySQLOperator import MySQLOperator

op = MySQLOperator()
data = op.get_pd_avg_decay_radio_by_day("c2e811465bf549598deba09538b3f0f9")

y_train = data['conservation_rate']
x_train = [[i]for i in range(len(y_train))]
# x_train = [[i]for i in range(50)]
print(len(x_train))

# 一次线性回归的学习与预测
# 线性回归模型 学习
regressor = LinearRegression()
regressor.fit(x_train, y_train)
# 画出一次线性回归的拟合曲线
xx = np.linspace(0, 100, 100)   # 0到16均匀采集100个点做x轴
xx = xx.reshape(xx.shape[0], 1)
yy = regressor.predict(xx)  # 计算每个点对应的y
# plt.scatter(x_train, y_train, color='green')   # 画出训练数据的点
# plt1, = plt.plot(xx, yy, label="degree=1")
# plt.axis([0, 70, 0.7, 1.2])
# plt.xlabel("Time")
# plt.ylabel("Regression")
# plt.legend(handles=[plt1])
# plt.show()

# 2次线性回归进行预测
poly2 = PolynomialFeatures(degree=2)    # 2次多项式特征生成器
x_train_poly2 = poly2.fit_transform(x_train)
# 建立模型预测
regressor_poly2 = LinearRegression()
regressor_poly2.fit(x_train_poly2, y_train)
# 画出2次线性回归的图
xx_poly2 = poly2.transform(xx)
yy_poly2 = regressor_poly2.predict(xx_poly2)

# 3次线性回归进行预测
poly3 = PolynomialFeatures(degree=3)    # 3次多项式特征生成器
x_train_poly3 = poly3.fit_transform(x_train)
# 建立模型预测
regressor_poly3 = LinearRegression()
regressor_poly3.fit(x_train_poly3, y_train)
# 画出3次线性回归的图
xx_poly3 = poly3.transform(xx)
yy_poly3 = regressor_poly3.predict(xx_poly3)

# 4次线性回归进行预测
poly4 = PolynomialFeatures(degree=4)    # 4次多项式特征生成器
x_train_poly4 = poly4.fit_transform(x_train)
# 建立模型预测
regressor_poly4 = LinearRegression()
regressor_poly4.fit(x_train_poly4, y_train)
# 画出4次线性回归的图
xx_poly4 = poly4.transform(xx)
yy_poly4 = regressor_poly4.predict(xx_poly4)


plt.scatter(x_train, y_train, color='yellow')
plt1, = plt.plot(xx, yy, label="Degree1")
plt2, = plt.plot(xx, yy_poly2, label="Degree2")
plt3, = plt.plot(xx, yy_poly3, label="Degree3")
plt4, = plt.plot(xx, yy_poly4, label="Degree4")
plt.axis([0, 100, 0.7, 1.2])
plt.xlabel("Time")
plt.ylabel("Regression")
plt.legend(handles=[plt1, plt2, plt3, plt4])
plt.show()
# 输出二次回归模型的预测样本评分
print("二次线性模型在训练数据上得分:", regressor_poly2.score(x_train_poly2, y_train))
print("三次线性模型在训练数据上得分:", regressor_poly3.score(x_train_poly3, y_train))
print("四次线性模型在训练数据上得分:", regressor_poly4.score(x_train_poly4, y_train))